"use strict";
const os = require('os'),
    fs = require('fs');

const bookDir = os.homedir() + '/Documents/Book/盗墓笔记';
const outFile = os.homedir() + '/Documents/Book/盗墓笔记.txt';

function strCompare(a, b) {
	var na = /^[0-9]+\..+$/.test(a);
	var nb = /^[0-9]+\..+$/.test(b);
	if (na && nb) {
		return parseInt(a.substring(0, a.indexOf("."))) - parseInt(b.substring(0, b.indexOf("."))); 
	} else if (na && !nb) {
		return -1;
	} else if (!na && nb) {
		return 1;
	} else {
		return a.localeCompare(b);
	}
}

var fd = fs.openSync(outFile, 'w+');
fs.readdir(bookDir, function(err, files){
	if (err) {
		console.error(err);
		fs.close(fd);
	} else {
		files = files.sort(strCompare);
		let volumnIndex = 0;
		for (let f of files) {
			let subDir = bookDir + "/" + f;
			if (!fs.statSync(subDir).isDirectory())
				continue;
			console.info(subDir);
			volumnIndex++;
			let volumn;
			if (/^[0-9]+\..+$/.test(f)) {
				volumn = f.substring(f.indexOf(".") + 1);
			} else
				volumn = f;
			

			fs.writeSync(fd, "第" + volumnIndex + "卷 " + volumn + '\n\n');

			let bookFiles = fs.readdirSync(subDir);
			bookFiles = bookFiles.sort(strCompare);
			for (let b of bookFiles) {
				if (/^\./.test(b))
					continue;
				let chapter;
				if (/^[0-9]+\..+$/.test(b)) {
					chapter = b.substring(b.indexOf(".") + 1);
				} else
					chapter = b;
				if (/^.+\.txt$/.test(chapter)) {
					chapter = chapter.substring(0, chapter.length - 4)
				}
				fs.writeSync(fd, chapter + '\n\n');
				let bookFile = subDir + "/" + b;
				let content = extractText(fs.readFileSync(bookFile, {"encoding": "utf-8", "flag": "r"}), bookFile);
				fs.writeSync(fd, content + '\n\n');
			}
		}
		fs.close(fd);
	}
});

// This function should be customized!!!
function extractText(content, filename) {
	let matcher = /<p style="text-indent:2em;">/gim.exec(content);
	let start;
	if (matcher == null) {
		console.error("content not found: " + filename);
		return "";
	}
	content = content.substring(matcher.index);
	matcher = /<!-- wei-xin -->/gim.exec(content);
	if (matcher != null) {
		content = content.substring(0, matcher.index);
	} else {
		matcher = /<p class="shangxia">/gim.exec(content);
		if (matcher != null) {
			content = content.substring(0, matcher.index);
		}
	}
	content = content.replace(/<br>|<\/p>|&[a-z]+;|<[^<>]+>/gim, function(matched){
		if (matched === '<br>' || matched === '</p>')
			return '\n';
		else if (matched === '&nbsp;') 
			return ' ';
		else if (matched === '&lt;')
			return '<';
		else if (matched === '&gt;')
			return '>';
		else if (matched === '&amp;')
			return '&';
		else if (matched === '&quot;')
			return '"';
		else if (matched === '&apos;')
			return '\'';
		else
			return '';
	});
	return content;
}
